<template>
  <div class="payment-container">
    <el-page-header @back="router.go(-1)">
      <template #content>
        <span class="text-large font-600 mr-3">订单支付</span>
      </template>
    </el-page-header>

    <el-alert v-if="error" type="error" :title="error.message" show-icon />

    <div v-if="paymentData" class="payment-content">
      <el-descriptions title="支付信息" border :column="2">
        <el-descriptions-item label="订单编号">{{ paymentData.orderId }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ paymentData.productName }}</el-descriptions-item>
        <el-descriptions-item label="商品单价">¥{{ paymentData.productPrice.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="购买数量">{{ paymentData.quantity }}件</el-descriptions-item>
        <el-descriptions-item label="订单总额">¥{{ paymentData.totalAmount.toFixed(2) }}</el-descriptions-item>
      </el-descriptions>

      <el-descriptions title="商品信息" border style="margin-top:20px">
        <el-descriptions-item label="商品图片">
          <el-image 
            :src="apiBase + '/product_images/' + paymentData.productImage"
            fit="contain"
            style="width:200px;height:200px"
          />
        </el-descriptions-item>
      </el-descriptions>

      <div class="payment-actions">
        <el-button 
          type="primary" 
          size="large"
          @click="handlePayment"
          :loading="paying"
        >立即支付</el-button>
        <el-button 
          type="danger" 
          size="large"
          @click="router.push('/orders')"
          style="margin-left: 20px"
        >拒绝支付</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/storage'

const route = useRoute()
const apiBase = ref(import.meta.env.VITE_API_BASE || '')
const error = ref<Error | null>(null)
const paying = ref(false)
const router = useRouter()

interface PaymentData {
  orderId: string
  productName: string
  productPrice: number
  totalAmount: number
  quantity: number
  productImage: string
}

const paymentData = ref<PaymentData>({
  orderId: route.query.orderId as string,
  productName: route.query.productName as string,
  productPrice: Number(route.query.productPrice),
  totalAmount: Number(route.query.totalAmount),
  quantity: Number(route.query.quantity),
  productImage: route.query.productImage as string
})

const handlePayment = async () => {
  try {
    paying.value = true
    const response = await fetch(`${apiBase.value}/pay`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${getToken()}`
      },
      body: JSON.stringify({
        orderId: paymentData.value.orderId,
        orderTotalAmount: paymentData.value.totalAmount
      })
    });

    if (!response.ok) {
      throw new Error(await response.text());
    }

    const result = await response.text();
    const parser = new DOMParser();
    const doc = parser.parseFromString(result, 'text/html');
    const form = doc.querySelector('form');

    if (form) {
      document.body.innerHTML = '';
      document.body.appendChild(form);
      form.submit();
    } else {
      ElMessage.error('支付页面加载失败');
    }
  } catch (err) {
    console.error('支付请求失败:', err)
    error.value = {
      name: 'PaymentError',
      message: (err as any)?.response?.data?.message || (err as Error)?.message || '未知支付错误',
      stack: (err as Error)?.stack
    }
    ElMessage.error(`支付失败：${error.value.message}`)
  } finally {
    paying.value = false
  }
}
</script>

<style scoped>
.payment-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.payment-actions {
  margin-top: 40px;
  text-align: center;
}
</style>